<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">大学生创新创业成果转化服务平台</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
      <div>
        <p style="font-size:15px;text-align: center">2023 © 渤海大学创新创业学院</p>
      </div>
    </el-form>
    <!--  底部  -->
   <!-- <div class="el-login-footer">
      <span>Copyright © 2018-2022 ruoyi.vip All Rights Reserved.</span>
    </div>-->
  </div>
</template>

<script>
const ExpiresInKey = 'sidebarStatus'
const ExpiresInKey1 = 'Admin-Token'

import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'

export default {
  name: "Login",
  data() {
    return {
      user: '',
      // 以下websocket
      wsIsRun: false,
      // 定义ws对象
      webSocket: null,
      // ws连接次数
      wsNumber: 0,
      // ws请求链接（类似于ws后台地址）
      ws: '',
      // ws定时器
      wsTimer: null,
      // 以上websocket
      unreadMsgNums: 0,
      unreadMsgNumsShow: '',
      hasConnected: false,
      codeUrl: "",
      loginForm: {
        username: "2021009003",
        password: "123456@bhu",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.wsIsRun = true
    this.wsNumber = 1
    /*Cookies.remove(ExpiresInKey)
    Cookies.remove(ExpiresInKey1)*/
    // this.getCode();
    // this.getCookie();
    this.pwdLogin()
  },
  methods: {
    /**
     * 初始化ws
     */
    wsInit() {
      // console.log("userName: " + this.$store.state.user.ipp)
      console.log("user: " + this.$store.state.constip.ipp)
      console.log("user: " + this.ipAddress)
      // const wsuri = 'ws://' + '210.47.178.218' + ':8080/library/wsService/' + this.$store.state.user.name
      this.getConfigKey("sys.account.ip").then(response => {
        this.sysipp = response.msg;
      });
      console.log("sysipp: " + this.sysipp)
      const wsuri = 'ws://' + this.sysipp + '/library/wsService/' +
        this.$store.state.constip.ipp + "_" + Math.floor(Math.random() * (99999 - 10000) + 10000)
      console.log("wsuri: " + wsuri)
      this.ws = wsuri
      if (!this.wsIsRun)
        return
      // 销毁ws
      this.wsDestroy()
      // 初始化ws
      this.webSocket = new WebSocket(this.ws)
      // ws连接建立时触发
      this.webSocket.addEventListener('open', this.wsOpenHanler)
      // ws服务端给客户端推送消息
      this.webSocket.addEventListener('message', this.wsMessageHanler)
      // ws通信发生错误时触发
      this.webSocket.addEventListener('error', this.wsErrorHanler)
      // ws关闭时触发
      this.webSocket.addEventListener('close', this.wsCloseHanler)

      clearInterval(this.wsTimer);
    },
    subSend(userId) {

      //获取msg的value
      // var msg = document.getElementById("msg").value;

      this.webSocket.send(userId);

      // ws服务端给客户端推送消息

      // document.getElementById("msg").value="";
    },


    wsOpenHanler(event) {
      console.log('ws建立连接成功')
    },
    wsMessageHanler(e) {
      console.log('wsMessageHanler')
      console.log(e)
      //Cookies.set('unreadNums', '6')

      this.openMsg(e)
      //const redata = JSON.parse(e.data)
      //console.log(redata)

    },
    /**
     * ws通信发生错误
     */
    wsErrorHanler(event) {
      console.log(event, '通信发生错误')
      console.log("第" + this.wsNumber + "次断线重连(5次未连接将自动断开)")
      this.wsNumber++
      if (this.wsNumber < 6) this.wsInit();
      //this.wsInit()
    },
    /**
     * ws关闭
     */
    wsCloseHanler(event) {
      console.log(event, 'ws关闭')
      console.log("websocket连接超时，已自动断开")
      //this.wsInit()
    },
    /**
     * 销毁ws
     */
    wsDestroy() {
      console.log("hello world")
      if (this.webSocket !== null) {
        this.webSocket.removeEventListener('open', this.wsOpenHanler)
        this.webSocket.removeEventListener('message', this.wsMessageHanler)
        this.webSocket.removeEventListener('error', this.wsErrorHanler)
        this.webSocket.removeEventListener('close', this.wsCloseHanler)
        this.webSocket.close()
        this.webSocket = null
        clearInterval(this.wsTimer)
        console.log("zoul111")
      } else {
        console.log("zoul")
      }
    },
    ClosesubSend(a){
      this.webSocket.send(a);
    },
    studentSubSend(a){
      this.webSocket.send(a);
    },
    collegeSubSend(a){
      this.webSocket.send(a);
    },
    enterpriseSubSend(a){
      this.webSocket.send(a);
    },



    /**
     * 弹窗
     */
    openMsg(e) {
      // alert("1")
      const h = this.$createElement;
      if (e.data) {
        alert(e.data)
        console.log(e.data)
        /*var dv = document.getElementById("dv");
        dv.innerHTML += e.data + " ";*/
        /*this.$router.push({path: "/"});*/
        if(e.data==1) {
          this.$router.push({path: "/dashujuzhanshi/dashujushouye"})
        }
        else if(e.data==2){
          this.$router.push({path: "/shou"})
        }else if(e.data==3){
          this.$router.push({path: "/mwnhugongshi"})
        }else if(e.data==4){
          this.$router.push({path: "/liucheng"})
        }else if(e.data==5){
          this.$router.push({path: "/dashujuzhanshi/xueyuan"})
        }else if(e.data==6){
          this.$router.push({path: "/dashujuzhanshi/nianfen"})
        }else if(e.data==21){

          this.$router.push({path: "/ykqlogin3"})
        }  else if(e.data==22){
          this.$router.push({path: "/ykqlogin4"})
        }else if(e.data==23){
          this.$router.push({path: "/ykqlogin5"})
        }else if(e.data==24){
          this.$router.push({path: "/shou"})
        }else if(e.data==210){
          this.$router.push({path: "/index"})
        }else if(e.data==211){
          this.$router.push({path: "/transformation"})
        }else if(e.data==212){
          this.$router.push({path: "/wodehetong"})
        }else if(e.data==213){
          this.$router.push({path: "/expense"})
        }else if(e.data==214){
          this.$router.push({path: "/qiye"})
        }else if(e.data==215){
          this.$router.push({path: "/geren"})
        }else if(e.data==216){
          this.$router.push({path: "/chengguogongshi"})
        }else if(e.data==217){
          this.$router.push({path: "/daochuxinxi"})
        }else if(e.data==218){
          this.$router.push({path: "/resultapply"})
        }else if(e.data==10){
          window.scrollBy(0, 100);
        }else if(e.data==11){
          window.scrollBy(0, -100);
        }else if(e.data==12){
          this.queryParams.signingStatus="0";

        }else if(e.data==13){
          this.queryParams.signingStatus="1";

        }else if(e.data>500&&e.data<2000){
          let nianfen=e.data-500
          this.$router.push({path: "/detail",query: {nianfen}})

        }else if(e.data>2000&&e.data<3000){
          let nianfen=e.data
          this.$router.push({path: "/dashujuzhanshi/xueyuan",query: {nianfen}})

        }else if(e.data>3000&&e.data<4000){
          let firstcollege=e.data
          let i_xueyuan=firstcollege-3000
          let xueyuan = '';
          if(i_xueyuan<10){
            xueyuan='00'+i_xueyuan;
          }else if(i_xueyuan>=10 && i_xueyuan<100){
            xueyuan='0'+i_xueyuan;
          }else{

          }
          this.$router.push({path: "/dashujuzhanshi/nianfen",query: {xueyuan}})


        }
        else{
          let userId=e.data
          this.$router.push({path: "/view",query: {userId}})

        }


        var data = JSON.parse(e.data)
        var route = this.$router;
        var msgType = data.msgType;
        /*if (msgType == "push") {
          // 如果是推送的是一条消息
          this.unreadMsgNums++;
          if (this.unreadMsgNums > 99) {
            this.unreadMsgNumsShow = "99+";
          } else {
            this.unreadMsgNumsShow = String(this.unreadMsgNums);
          }

          this.$notify.info({
            title: data.msgTitle,
            message: data.msgContent,
            onClick() {
              console.log(route)
              route.push({path: "/library/yyg/msg/list"});
            }
          });
        } else if (msgType == "unread") {
          // 如果推送的是未读消息数
          //Cookies.set('unreadNums', data.unreadNums);
          this.unreadMsgNums = Number(data.unreadNums);
          if (this.unreadMsgNums > 0) {
            this.unreadMsgNumsShow = String(this.unreadMsgNums);
            if (this.unreadMsgNums > 99) {
              this.unreadMsgNumsShow = "99+";
            }
            this.$notify.info({
              title: "消息提醒",
              //message: data.msgContent,
              message: "您当前有" + this.unreadMsgNumsShow + "条未读消息，点击此处查看",
              onClick() {
                console.log(route)
                route.push({path: "/library/yyg/msg/list"});
              }
            });
          }
        } else if (msgType == "read") {
          // 如果推送的是用户已读消息
          this.unreadMsgNums--;
          if (this.unreadMsgNums > 0 && this.unreadMsgNums <= 99) {
            this.unreadMsgNumsShow = String(this.unreadMsgNums);
          } else if (this.unreadMsgNums <= 0) {
            this.unreadMsgNumsShow = '';
          }
        }
*/
      }
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    // 密码登录
    async pwdLogin() {
      this.$store.dispatch('Login', this.loginForm).then(() => {
        this.loginSuccess()
      })
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
      // 设置用户信息
      this.$store.dispatch('GetInfo').then(res => {
        this.$router.push({path: "/index"})
        setTimeout(() => {
          location.reload();
        }, 1000);
        // this.$tab.reLaunch('/pages/module/wtc/index?table=21')
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({path: "/index"});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
